<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryProps.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="depTree"
          node-key="id"
          :highlight-current="true"
          :expand-on-click-node="false"
          default-expand-all
          :props="defaultProps"
          :data="departmentList"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table border stripe :data="employeeList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{row}">
              <el-avatar v-if="row?.staffPhoto" shape="circle" :size="size" :src="row?.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <span>{{ row.formOfEmployment === 1 ? "正式" : row.formOfEmployment === 2 ? "非正式" : "无" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确认删除该行数据吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px;" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px;">
          <el-pagination
            background
            :page-size="queryProps.pagesize"
            :current-page="queryProps.page"
            :total="total"
            layout="total, prev, pager, next"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 导入弹窗 -->
    <import-excel-vue :show-excel-dialog.sync="showExcelDialog" @uploadSucess="getEmployeeList" />
    <el-dialog title="分配权限" :visible.sync="showDialog">
      <!-- 弹层内容 -->
      <!-- 展示角色 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row type="flex" justify="center" style="margin-top: 40px;">
        <el-button size="mini" type="primary" @click="btnOkey">确定</el-button>
        <el-button size="mini" @click="showDialog=false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>

</template>

<script>
import { getEmployeeList, exportEmployee, delEmployee, getRoleList, getEmployeeDetail, assignRoles } from '@/api/employee'
import { listToTreeDate } from '@/utils'
import { getDepartment } from '@/api/department'
import FileSaver from 'file-saver'
import importExcelVue from './components/import-excel.vue'

export default {
  name: 'Employee',
  // 注册组件
  components: {
    importExcelVue
  },

  data() {
    return {
      showDialog: false, // 控制分配权限弹窗
      showExcelDialog: false, // 控制导入弹窗
      // 存储可用角色
      roleList: [],
      roleIds: [], // 存储选中的角色
      currentId: null, // 记录当前点击的id
      // 存储员工数据
      employeeList: [],
      departmentList: [], // 部门列表
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryProps: {
        page: 1,
        pagesize: 10,
        departmentId: 0,
        keyword: '' // 根据名称模糊查询
      },
      total: 0, // 记录查询总数
      size: 40, // 定义头像大小
      timer: null // 定义 timer 变量
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const result = await getDepartment()
      // 递归方法 列表转化为树形结构
      this.departmentList = listToTreeDate(result, 0)
      this.queryProps.departmentId = this.departmentList[0].id
      // 设置选中的节点
      // 树组件的渲染是异步的
      this.$nextTick(() => {
        // 此时意味着dom已经渲染完成
        this.$refs.depTree.setCurrentKey(this.queryProps.departmentId)
      })
      // 此时已经记录了部门id
      this.getEmployeeList()
    },
    // 选择部门id 进行存储id 用于查询员工列表
    selectNode(node) {
      // console.log(node)
      this.queryProps.departmentId = node.id // 重新记录了参数
      // 页码归1
      this.queryProps.page = 1
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryProps)
      this.employeeList = rows // 重新记录员工列表
      this.total = total // 重新记录总数
    },
    // 切换页码
    changePage(newPage) {
      this.queryProps.page = newPage // 重新记录页码
      this.getEmployeeList()
    },
    // 搜索
    changeValue() {
      // 单位时间内只执行最后一次
      // this.实例上的方法
      if (this.timer) {
        clearTimeout(this.timer) // 清除上一次的定时器
      }
      this.timer = setTimeout(() => {
        this.queryProps.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出员工
    async exportEmployee() {
      const result = await exportEmployee() // 导出员工
      // console.log(result) // 使用一个npm包 直接讲blob流转化为文件下载 file-saver
      FileSaver.saveAs(result, '员工列表.xlsx')
    },
    // 删除员工
    async confirmDel(id) {
      await delEmployee(id) // 删除员工
      // 消息提示
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      // 判断删除的是否是最后一页的最后一条数据
      if (this.employeeList.length === 1 && this.queryProps.page > 1) {
        this.queryProps.page--
      }
      this.getEmployeeList()
    },
    // 分配角色
    async btnRole(id) {
      // 获取角色列表
      this.roleList = await getRoleList()
      // 记录当前点击的id 因为后面确定取消要存储
      this.currentId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showDialog = true
    },
    // 确定
    async btnOkey() {
      await assignRoles({
        id: this.currentId,
        roleIds: this.roleIds })
      // 提示消息
      this.$message({ message: '分配成功', type: 'success' })
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
